#pragma once

#include <mutex>
#include <queue>
#include <thread>
#include <chrono>
#include <vector>
#include <functional>
#include <unordered_map>

using EventHandler = std::function<void()>;
using TimeStamp = std::chrono::steady_clock::time_point;

struct Client {
    TimeStamp expire;
    EventHandler callback;

    Client(TimeStamp timeout, EventHandler callBack) : expire(timeout), callback(std::move(callBack)) {}

    bool operator<(const Client &other) const {
        return expire < other.expire;
    }

    bool operator>(const Client &other) const {
        return expire < other.expire;
    }
};

class Timer {
private:
    std::mutex mutex;
    std::priority_queue<Client, std::vector<Client>, std::greater<>> clients;  // 优先队列，小根堆
    std::unordered_map<int, Client> fd_to_client;                              // fd到client对象的映射
public:
    Timer();

    ~Timer();

    void add(int fd, std::chrono::milliseconds interval, const EventHandler &callback);

    void update(int fd, std::chrono::milliseconds interval);

    void clean_inactive_connection();
};
